from rest_framework.views import exception_handler
from rest_framework.response import Response
from django.db.models import ProtectedError, RestrictedError
from django.http import Http404
from rest_framework.exceptions import APIException as DRFAPIException, AuthenticationFailed, PermissionDenied
from rest_framework.views import set_rollback, exception_handler

def CustomExceptionHandler(ex, context):
    msg = f"no exception {ex.__class__.__name__}  {ex}"
    code = 500
    # 调用默认的异常处理函数
    response = exception_handler(ex, context)
    if isinstance(ex, AuthenticationFailed):
        # 如果是身份验证错误
        if response and response.data.get("detail") == "Given token not valid for any token type":
            return Response({'code': 401, 'msg': 'Given token not valid for any token type'})
        elif response and response.data.get("detail") == "Token is blacklisted":
            # token在黑名单
            return Response({'code': 401, 'msg': 'Token is blacklisted'})
        else:
            code = 401
            msg = ex.detail
            return Response({'code': code,'msg': msg}, status=200)
    elif isinstance(ex, PermissionDenied):
        # 如果是权限错误
        code = 403
        msg = ex.detail
        return Response({'code': code,'msg': msg}, status=200)
    elif isinstance(ex, Http404):
        code = 400
        msg = "接口地址不正确"
        return Response({'code': code,'msg': msg}, status=200)
    elif isinstance(ex, DRFAPIException):
        set_rollback()
        msg = ex.detail
        if isinstance(ex, PermissionDenied):
            msg = f'{msg} ({context["request"].method}: {context["request"].path})'
        if isinstance(msg, dict):
            for k, v in msg.items():
                for i in v:
                    msg = "%s:%s" % (k, i)
    elif isinstance(ex, (ProtectedError, RestrictedError)):
        set_rollback()
        msg = "无法删除:该条数据与其他数据有相关绑定"
    
    return Response({'code': code,'msg': msg}, status=200)
